import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import qs from 'qs';
import _ from 'lodash';
import moment from 'moment';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Table,
  Button,
  Card,
  Col,
  Row,
  Select,
  Modal,
  Input,
  DatePicker,
  message,
  Divider,
  Tooltip,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

const { Item } = Form;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { pathname } = window.location;

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  logisCenterDeliveryHistoryList: any;
  INITINFO: any;
  loading: boolean;
  screen: string;
}

interface TableListState {
  current: number;
  pageSize: number | undefined;
  formValues: any;
  exportInfo: any;
  exportDialog: boolean;
  rowId:number;
}

const deliveryObj = {
  1: '柜体投递',
  3: '扫描枪投递',
  4: '快递员APP投递',
  5: '投递员小程序',
  6: '投递员小程序OCR',
  7: '物流中心OCR',
  8: '投递员小程序驿站',
  9: '投递员小程序驿站OCR',
  10: '近邻助手OCR投递',
};

/* eslint react/no-multi-comp:0 */
@connect(({
  logisCenterDeliveryHistoryList,
  common: { INITINFO },
  global: { screen },
  loading,
}: any) => ({
  logisCenterDeliveryHistoryList,
  INITINFO,
  screen,
  loading: loading.effects['logisCenterDeliveryHistoryList/fetch'],
}))
class TableList extends React.Component<TableListProps, TableListState> {
  columns: any= [
    {
      title: '运单号',
      dataIndex: 'expCode',
      width: 120,
      render: (expCode: any, record: any) => (
        <Tooltip title={expCode}>
          <div
            className="wordOmit nameLink"
            style={{ maxWidth: 120 }}
            onClick={() => this.handleShowDelivery(record.id, expCode)}
          >
            {expCode}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '收件人',
      dataIndex: 'consigneePhone',
      width: 100,
    },
    {
      title: '投递人',
      dataIndex: 'courierPhone',
      width: 100,
      render: (text: string) => text || '--',
    },
    {
      title: '入库时间',
      dataIndex: 'inTime',
      width: 140,
    },
    {
      title: '快递公司',
      dataIndex: 'expressName',
      width: 100,
    },
    {
      title: '投递类型',
      dataIndex: 'deliveryWay',
      width: 100,
      render: (text: number) => deliveryObj[text],
    },
    {
      title: '订单状态',
      dataIndex: 'statusName',
      width: 100,
    },
    {
      title: '操作',
      width: 100,
      fixed: 'right',
      render: (id: any, record: any) => (
        <div>
          <span
            className="operLink"
            onClick={() => this.handleShowDelivery(record.id, record.expCode)}
          >
            详情
          </span>
          <Divider type="vertical" />
          <span
            className="operLink"
            onClick={() => this.handleConfirmPickup(record)}
          >
            确认取走
          </span>
        </div>
      ),
    },
  ];

  state: TableListState = {
    current: 1,
    pageSize: 20,
    formValues: {},
    exportInfo: {},
    exportDialog: false,
    rowId: 0,
  };

  static getDerivedStateFromProps(props: any, state: any) {
    const { search } = props.location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { page, psize, ...formValues } = query;

    return {
      ...state,
      formValues,
      current: Number(page) || 1,
      pageSize: Number(psize) || 20,
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchGardenList();
    this.fetchExpressList();
    this.fetchHistoryList();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { formValues, current, pageSize } = this.state;
    if (!_.isEqual(formValues, prevState.formValues)
      || current !== prevState.current
      || pageSize !== prevState.pageSize) {
      this.setFieldsValue();
      this.fetchHistoryList();
    }
  }

  // 设置表单值
  setFieldsValue = () => {
    const { formValues: { queryMonth, ...others } } = this.state;

    if (queryMonth) {
      others.queryMonth = moment(queryMonth);
    } else {
      others.queryMonth = moment();
    }

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(others);
  }

  // 获取快递公司列表
  fetchGardenList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchLogisList',
      payload: { status: 1 },
    });
  }

  // 获取校园小区列表
  fetchExpressList = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'common/fetchExpressList' });
  }

  // 获取数据
  fetchHistoryList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterDeliveryHistoryList/fetch',
      payload: this.getQueryParams(),
    });
  }

  // 获取查询参数
  getQueryParams = () => {
    const { formValues, current, pageSize } = this.state;
    const params = { ...formValues };

    params.pageIndex = current;
    params.pageSize = pageSize;

    if (!params.queryMonth) params.queryMonth = moment().format('YYYY-MM');
    return params;
  };

  /**
   * 查询
   */
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;

      if (fieldsValue.queryMonth) {
        fieldsValue.queryMonth = moment(fieldsValue.queryMonth).format('YYYY-MM');
      }

      const query = { page: 1, ...fieldsValue };
      router.push({ pathname, query });

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '查询历史订单',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  /**
   * 重置
   */
  handleFormReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '查询历史订单',
      url: pathname,
      isTopMenu: true,
    });
  };

  /**
   * 打开导出弹窗
   */
  handleOpenExport = () => this.setState({ exportDialog: true });

  /**
   * 关闭导出弹窗
   */
  handleCloseExport = () => this.setState({
    exportDialog: false,
  });

  /**
   * 导出派件数据
   */
  handleExportHistory = () => {
    const { exportInfo } = this.state;
    if (!exportInfo.logisId) {
      message.error('请选择物流中心！');
      return;
    }

    if (!exportInfo.expressId) {
      message.error('请选择快递公司！');
      return;
    }

    if (!exportInfo.startDate) {
      message.error('请选择起止时间！');
      return;
    }

    if (!exportInfo.sendTo) {
      message.error('请输入收件人邮箱！');
      return;
    }

    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterDeliveryHistoryList/export',
      payload: exportInfo,
    }).then((res:any) => {
      if (res) {
        message.success(res.msg);
        this.handleCloseExport();
      }
    });
  };

  /**
   * 查看快递
   */
  handleShowDelivery = (id: number, expCode: string) => {
    const { dispatch } = this.props;

    addTab(dispatch, {
      name: `查看${expCode}`,
      url: `/logisCenter/delivery/list/detail/${id}`,
    });
  };

  /**
   * 确定取走
   */
  handleConfirmPickup = (orderInfo: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterDeliveryHistoryList/pickup',
      payload: { id: orderInfo.id },
    });
  };

  // 分页
  onSelectChange = (current: number, pageSize: number | undefined) => {
    const { formValues } = this.state;
    const query = {
      ...formValues,
      page: current,
      psize: pageSize,
    };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '查询历史订单',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  /**
   * 输入运单号
   */
  handleChangeExpCode = (e: any) => {
    const { exportInfo } = this.state;
    exportInfo.expCode = e.target.value;

    this.setState({ exportInfo });
  }

  /**
   * 选择物流中心
   */
  handleChangeLogis = (value: string) => this.changeExportInfo('logisId', value);

  /**
   * 选择快递公司
   */
  handleChangeExpress = (value: string) => this.changeExportInfo('expressId', value);

  /**
   * 选择起止时间
   */
  handleChangeDate = (date: any, dateArr: any) => {
    const { exportInfo } = this.state;
    [exportInfo.startDate, exportInfo.endDate] = dateArr;
    this.setState({ exportInfo });
  }

  /**
   * 输入收件人邮箱
   */
  handleChangeEmail = (e: any) => this.changeExportInfo('sendTo', e.target.value);

  changeExportInfo = (key:string, value:any) => {
    const { exportInfo } = this.state;
    exportInfo[key] = value;
    this.setState({ exportInfo });
  }

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  // 渲染查询表单
  renderSearchFormElem = () => {
    const { form: { getFieldDecorator } } = this.props;

    return (
      <Form onSubmit={this.handleSearch} className="tableListForm">
        <Row gutter={12}>
          <Col md={8} sm={24}>
            <Item label="订单投递月份" colon={false}>
              {getFieldDecorator('queryMonth')(
                <DatePicker
                  placeholder="请选择"
                  style={{ width: '100%' }}
                  format="YYYY-MM"
                />,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Item label="　　　运单号" colon={false}>
              {getFieldDecorator('expCode')(
                <Input placeholder="请输入" />,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <div className="flexFeView">
              <Button
                type="primary"
                htmlType="submit"
                className="smallButton"
              >
                查询
              </Button>
              <Button
                type="primary"
                className="addButton marginL16 smallButton"
                onClick={this.handleFormReset}
              >
                重置
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  // 渲染追回件弹窗
  renderExportModalElem = () => {
    const { exportDialog } = this.state;
    const { INITINFO: { expressList, logisList } } = this.props;

    return (
      <Modal
        title="导出历史派件记录"
        visible={exportDialog}
        onOk={this.handleExportHistory}
        onCancel={this.handleCloseExport}
      >
        {exportDialog && (
          <Form className="tableListForm">
            <Row>
              <Col md={20} sm={20}>
                <Item label="　物流中心" colon={false}>
                  <Select
                    showSearch
                    placeholder="请选择"
                    optionFilterProp="children"
                    onChange={this.handleChangeLogis}
                    filterOption={(input: any, option: any) => (
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    )}
                  >
                    {logisList.map((item: any) => (
                      <Option
                        value={item.id}
                        key={item.id}
                      >{item.name}
                      </Option>
                    ))}
                  </Select>
                </Item>
              </Col>
            </Row>
            <Row>
              <Col md={20} sm={20}>
                <Item label="　快递公司" colon={false}>
                  <Select
                    showSearch
                    placeholder="请选择"
                    optionFilterProp="children"
                    onChange={this.handleChangeExpress}
                    filterOption={(input: any, option: any) => (
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    )}
                  >
                    {expressList.map((item: any) => (
                      <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                    ))}
                  </Select>
                </Item>
              </Col>
            </Row>
            <Row>
              <Col md={20} sm={20}>
                <Item label="　起止时间" colon={false}>
                  <RangePicker
                    style={{ width: '100%' }}
                    placeholder={['开始时间', '截止时间']}
                    ranges={{
                      今天: [moment().startOf('day'), moment().endOf('day')],
                      本周: [moment().startOf('week'), moment().endOf('week')],
                      本月: [moment().startOf('month'), moment().endOf('month')],
                      上月: [
                        moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                        moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                      ],
                    }}
                    onChange={this.handleChangeDate}
                  />
                </Item>
              </Col>
            </Row>
            <Row>
              <Col md={20} sm={20}>
                <Item label="收件人邮箱" colon={false}>
                  <Input
                    placeholder="test@jinlinbao.com"
                    onChange={this.handleChangeEmail}
                  />
                </Item>
              </Col>
            </Row>
          </Form>
        )}
      </Modal>
    );
  }

  render() {
    const { current, pageSize } = this.state;
    const { logisCenterDeliveryHistoryList: { data }, screen, loading } = this.props;

    const pagination = data
      ? {
        total: data ? data.count : 0,
        pageSize,
        current: current || 1,
        onChange: this.onSelectChange,
        showTotal: () => `共${data.count || 0}条数据`,
        showQuickJumper: true,

        pageSizeOptions: ['10', '20', '50', '100'],
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    const { columns } = this;
    if (screen === 'sm' || screen === 'lg') {
      delete this.columns[columns.length - 1].fixed;
    } else if (screen === 'md') {
      this.columns[columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />
        <Card bordered={false} className="searchForm">
          {this.renderSearchFormElem()}
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={this.handleOpenExport}
            >
              导出历史派件数据
            </Button>
          </div>

          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={columns}
            dataSource={data.list || []}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1300 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        {this.renderExportModalElem()}
      </>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
